#include "SSD1306Wire.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "Ticker.h"；

#define SDA_PIN 0                       // SDA引脚，默认gpio4(D2)
#define SCL_PIN 2                       // SCL引脚，默认gpio5(D1)

//-----------------------变量部分-------------------------------
//配置变量
const int I2C_ADDR = 0x3c;             
const char* ssid = "Mi10";
const char* password = "13960379768czy";
const char* mqtt_server = "192.168.27.180";
//设备详情
String deviceId = "4444dddd";
String deviceType = "温度监控灯";
String location = "客厅";
String clientId = "8266:" + deviceType + ":" + deviceId;  
//绑定设备ID
String bindDeviceId = "2222bbbb";
//显示变量
String temp = "Temp:";
String humidity = "Humidity:";
int _tempeature = 0;  
int _humidity = 10;
//顶级变量
WiFiClient espClient;
PubSubClient client(espClient);
SSD1306Wire oled(I2C_ADDR, SDA_PIN, SCL_PIN);
Ticker myTicker;
//--------------------------------------------------------------



//----------------------函数部分---------------------------------
//连接mqtt
void reconnect();
//连接WiFi
void setup_wifi();
//oled初始化
void oled_init();
//回调
void callback(char* topic, byte* payload, unsigned int length);
//根据payload转化消息String
String getMsgStringByPayload(byte* payload,int length);
//发送注册信息
void sendRegisterMsg();
//获取注册信息的jsonString
String getRegisterJsonString();
//心跳任务
void tickerHandle();
//订阅主题
void subscribeTopic();
//解析Temperature_Humidity发送的JsonString
void resolveMessage(String str);
//--------------------------------------------------------------


void setup() {
  /* 1. 初始化串口通讯波特率为115200*/
  Serial.begin(9600);
  //2WIFI初始化
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  myTicker.attach(3, tickerHandle);
  oled_init();
}


void loop() {
   if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

//连接mqtt
void reconnect() {
//  oled.clear(); 
//  oled.drawString(0, 0, "Connect Mqtt...");
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    
    if (client.connect(clientId.c_str(),"OFFLINE",1,false,deviceId.c_str())) {
      Serial.println("connected");
      //发送注册消息
      sendRegisterMsg();
      //发送心跳
      client.publish("Heart",deviceId.c_str()) ;
      //订阅消息主题 
      subscribeTopic();
//      oled.clear(); 
//      oled.drawString(0, 0, "Success connect");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
//      oled.drawString(0, 0, "Fail connect");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//oled初始化
void oled_init()
{
    /*4. oled屏幕初始化 */
  oled.init();
  oled.setFont(ArialMT_Plain_16);     // 设置字体
  oled.flipScreenVertically();        // 设置屏幕翻转
  oled.setContrast(255);              // 设置屏幕亮度
  //drawRect();                         // 测试屏幕显示
  oled.clear(); 
  oled.display();       // 清除屏幕  
}
//链接WiFi
void setup_wifi()
{
  delay(10);
//  oled.clear(); 
//  oled.drawString(0, 0, "Connect wifi...");
  //We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());  
//  oled.clear(); 
//  oled.drawString(0, 0, "Success connect");
}
//回调函数
void callback(char* topic, byte* payload, unsigned int length) 
{
  String strTopic = String(topic);
  String msgStr = getMsgStringByPayload(payload,length);
  Serial.println("Arrived||Topic:"+strTopic + "  Msg:" + msgStr);
  //
  if(strTopic == "Temperature_Humidity"){
      //解析并改变温湿度
      resolveMessage(msgStr);
  }
}
//根据payload转化消息String
String getMsgStringByPayload(byte* payload,int length)
{
  String msgStr;
  for (int i = 0; i < length; i++) {
    msgStr +=(char)payload[i];
  }
  return msgStr;
}
//发送注册消息的msg
void sendRegisterMsg()
{
    String registerStr = getRegisterJsonString();
    Serial.println("Register:" + registerStr);
    client.publish("register_device",registerStr.c_str());
}
//获取注册信息的Json并转化为String
String getRegisterJsonString()
{
    String registerStr;
    StaticJsonDocument<200> doc;
    doc["deviceId"] = deviceId;
    doc["deviceType"] = deviceType;
    doc["online"] = "1";
    doc["location"] = location;
    serializeJson(doc, registerStr);
    return registerStr;
}
//定时任务
void tickerHandle()
{
  client.publish("Heart",deviceId.c_str()) ;  
}
//订阅主题
void subscribeTopic(){
  client.subscribe("Temperature_Humidity");
}
//解析Temperature_Humidity发送的JsonString
void resolveMessage(String str)
{
  String deviceStr;
  const size_t capacity = JSON_OBJECT_SIZE(4) + 70;
  DynamicJsonDocument doc(capacity);
  deserializeJson(doc, str);
  //判断和绑定的ID是否相等
  deviceStr = doc["deviceId"].as<String>();
  Serial.println("Here");
  if(bindDeviceId != deviceStr)
  {
    return;
  }
  oled.clear(); 
  _tempeature    =  doc["temperature"].as<int>();
  _humidity  =  doc["humidity"].as<int>();
  Serial.println("Here:" + String(_tempeature) + String(_humidity));
  oled.drawString(0, 0, "       Show  "); 
  oled.drawString(0, 16, temp + String(_tempeature));     // 将要显示的文字写入缓存
  oled.drawString(0, 32, humidity + String(_humidity)); 
  oled.display();                     // 将缓存里的文字在屏幕上显示
}
